#include "ServerThread.h"

ServerThread::ServerThread(QTcpSocket *tcpSocket)
{
    this->tcpSocket = tcpSocket;
}
void ServerThread::run()
{
    // 获取当前线程的 ID 并转换为字符串
    // quintptr threadId = reinterpret_cast<quintptr>(QThread::currentThreadId());
    // QString connectionName = QString("newThread_%1").arg(threadId);
    // qDebug() << "新线程创建：" << connectionName;

    // 将 tcpSocket 移动到当前线程
    // tcpSocket->moveToThread(this);

    PptpSocket *pptpSocket = new PptpSocket(tcpSocket); // 创建 PptpSocket

    // 获取 PptpSocket 所在的线程
    // QThread *socketThread = pptpSocket->thread();
    // quintptr socketThreadId = reinterpret_cast<quintptr>(socketThread->currentThreadId());
    // QString socketThreadName = QString("PptpSocket Thread: %1").arg(socketThreadId);
    // qDebug() << "pptpSocket所在线程：" <<socketThreadName;

    // 处理数据读取的信号
    connect(pptpSocket, &PptpSocket::readCompletedSignal, this, [pptpSocket](QByteArray readMessage)
            {
                // 获取当前线程的 ID 并转换为字符串
                // quintptr threadId = reinterpret_cast<quintptr>(QThread::currentThreadId());
                // QString connectionName = QString("ThreadId_%1").arg(threadId);
                // qDebug() << "当前处理信号的线程为：" << connectionName;

                PptpServerRoute pptpServerRoute;
                QByteArray writeMessage = pptpServerRoute.dispatchRequest(readMessage); // 处理消息
                pptpSocket->pptpWrite(writeMessage);                                    // 回复客户端
            });

    // 处理客户端断开连接的信号
    connect(pptpSocket, &PptpSocket::pptpDisconnect, this, [this, pptpSocket]()
            {
                pptpSocket->deleteLater();            // 当连接断开时删除 socket
                emit threadEnd(); });

    pptpSocket->onReadyRead();

    exec();
}
